import request from '@/utils/request'

/**
 * 发送短信验证码
 * @param {string} phone - 手机号
 * @returns {Promise<{success: boolean, data?: any, error?: string}>}
 */
export const sendSMSCode = async (phone) => {
  try {
    const response = await request({
      url: '/auth/send-code',
      method: 'POST',
      data: { phone }
    })
    
    return {
      success: true,
      data: response.data,
      status: response.status
    }
    
  } catch (error) {
    return {
      success: false,
      error: error.response?.data?.message || '验证码发送失败',
      status: error.response?.status
    }
  }
}

/**
 * 短信验证码登录
 * @param {string} phone - 手机号
 * @param {string} code - 验证码
 * @returns {Promise<{success: boolean, data?: any, error?: string}>}
 */
export const loginBySMS = async (phone, code) => {
  try {
    const response = await request({
      url: '/auth/login/sms',
      method: 'POST',
      data: { phone, code }
    })

    return {
      success: true,
      data: response.data,
      token: response.data?.token,  // 明确返回token字段
      status: response.status
    }
    
  } catch (error) {
    return {
      success: false,
      error: error.response?.data?.message || '短信登录失败',
      status: error.response?.status
    }
  }
}

/**
 * 密码登录
 * @param {string} phone - 手机号
 * @param {string} password - 密码
 * @returns {Promise<{success: boolean, data?: any, error?: string}>}
 */
export const loginByPassword = async (phone, password) => {
  try {
    const response = await request({
      url: '/auth/login/password',
      method: 'POST',
      data: { phone, password }
    })

    return {
      success: true,
      data: response.data,
      token: response.data?.token,  // 明确返回token字段
      status: response.status
    }
    
  } catch (error) {
    return {
      success: false,
      error: error.response?.data?.message || '密码登录失败',
      status: error.response?.status
    }
  }
}